# from diffusers import StableDiffusionPipeline
# import torch

# # 加载模型
# model_id = "runwayml/stable-diffusion-v1-5"
# pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
# pipe = pipe.to("cuda")  # 使用 GPU 加速

# # 文本描述
# prompt = "A fantasy landscape with mountains and rivers, in the style of Studio Ghibli"

# # 生成图像
# image = pipe(prompt).images[0]


import torch
from diffusers import StableDiffusionPipeline
 
# 初始化模型
model_id = "runwayml/stable-diffusion-v1-5"  # 也可以使用 v2-1 等其他版本
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to("cuda")  # 移动到 GPU 上，如果只有 CPU 则使用 "cpu"
 
# 生成图像
prompt = "一个美丽的山谷中有一座小木屋，周围是郁郁葱葱的森林和清澈的湖泊，阳光照射下的风景"
negative_prompt = "模糊，低质量，变形，扭曲"
 
image = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=50,
    guidance_scale=7.5
).images[0]
 
# 保存图像
image.save("generated_landscape.png")


import torch
from diffusers import StableDiffusionImg2ImgPipeline
from PIL import Image
 
# 初始化模型
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)
pipe = pipe.to("cuda")
 
# 加载初始图像
init_image = Image.open("F:\PythonBasic\PythonBasic\input_image.jpg").convert("RGB")
init_image = init_image.resize((768, 512))
 
# 生成新图像
prompt = "同一风景，但是在冬天，覆盖着雪"
image = pipe(
    prompt=prompt,
    image=init_image,
    strength=0.75,  # 控制变化的程度，0-1之间
    guidance_scale=7.5
).images[0]
 
image.save("winter_scene.png")

import torch
from diffusers import StableDiffusionPipeline
 
# 初始化模型
pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)
 
# 加载 LoRA 权重
# pipe.unet.load_attn_procs("path/to/your/lora/weights")

pipe.unet.load_attn_procs("sayakpaul/sd-model-finetuned-lora-t4")  # 替换为真实模型ID
pipe.unet.load_attn_procs("F:/models/lora_weights/pytorch_lora_weights.bin")
pipe = pipe.to("cuda")
 
# 生成图像
prompt = "使用特定风格的图像"
image = pipe(prompt=prompt).images[0]
image.save("lora_style_image.png")



# -*- coding: utf-8 -*-
"""
Stable Diffusion 图像生成完整示例
环境要求：Python 3.8+, torch 2.0+, diffusers 0.20+
"""

import torch
from diffusers import StableDiffusionPipeline
import os

# 设置代理（如果需要访问Hugging Face）
# os.environ["HTTP_PROXY"] = "http://127.0.0.1:10809"
# os.environ["HTTPS_PROXY"] = "http://127.0.0.1:10809"

def generate_image(prompt, model_name="runwayml/stable-diffusion-v1-5", lora_weights=None):
    # 自动检测设备
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Using device: {device}")
    
    try:
        # 1. 加载基础模型
        pipe = StableDiffusionPipeline.from_pretrained(
            model_name,
            torch_dtype=torch.float32 if device == "cpu" else torch.float16
        ).to(device)
        
        # 2. 加载LoRA权重（可选）
        if lora_weights:
            # 支持本地路径或Hugging Face模型ID
            pipe.unet.load_attn_procs(lora_weights)
            print(f"Loaded LoRA weights from: {lora_weights}")

        # 3. 生成图像
        print("Generating image...")
        image = pipe(
            prompt,
            num_inference_steps=50,
            guidance_scale=7.5
        ).images[0]
        
        # 4. 保存结果
        output_path = "generated_image.png"
        image.save(output_path)
        print(f"Image saved to: {output_path}")
        return output_path
        
    except Exception as e:
        print(f"Error: {str(e)}")
        return None

if __name__ == "__main__":
    # 使用示例（默认参数）
    prompt = "A futuristic cityscape during sunset, digital art, 4k resolution"
    
    # 选项1：使用基础模型
    generate_image(prompt)
    
    # 选项2：使用LoRA模型（示例模型）
    # generate_image(prompt, lora_weights="sayakpaul/sd-model-finetuned-lora-t4")



